import React, { Component } from 'react';
import { TouchableOpacity, Alert, View, StyleSheet, ScrollView } from 'react-native';
import { ButtonGroup, CheckBox, Text, Button, List, ListItem } from 'react-native-elements';
import { primaryColor, toast, checkoutNextPage } from './utils';
import { setCheckoutSelect, getCheckoutSelect } from './clientStorage';
import CreditCardList from './components/CreditCardList';
import CreditPaymentOption from './components/CreditPaymentOption';
import NavNext from './widgets/NavNext';
import moment from 'moment';

const styles = StyleSheet.create({
  header: {
    margin: 8
  },
  list: {
    marginTop: 0
  },
  listButton: {
    textAlign: 'center',
    color: primaryColor
  }
});

class CheckoutPaymentPage extends Component {
  static navigationOptions = ({navigation, screenProps}) => {
    return {
      title: `${screenProps.chinese?'选择支付方式':'Payment'} (${navigation.state.params.stepIndex+1}/${navigation.state.params.stepper.length})`,
      headerRight: (
        <NavNext chinese={screenProps.chinese} onPress={() => {
            if (!navigation.state.params.payment) return toast(screenProps.chinese?'请选择支付方式':'Please select a payment option');
            if (navigation.state.params.voucher&&navigation.state.params.promoCode) return toast(screenProps.chinese?'每个订单只能使用一种促销方式':'You can only use one promotion at a time');

            checkoutNextPage(navigation, {
              voucherId: navigation.state.params.voucher&&navigation.state.params.voucher.id,
              promoCodeId: navigation.state.params.promoCode&&navigation.state.params.promoCode.id
            });
          }}/>
      ),
    };
  };
  state = {}
  onAddCard = () => this.props.navigation.navigate('AddCreditCard')
  onSelectCreditCard = (card) => this.props.navigation.setParams({payment: card.id})
  onSelectCredit = () => this.props.navigation.setParams({payment: 'credit'})
  onSelectCash = () => this.props.navigation.setParams({payment: 'cash'})
  onSelectPaypal = () => this.props.navigation.setParams({payment: 'paypal'})
  onSelectVoucher = () => {
    if (this.props.navigation.state.params.promoCode) {
      Alert.alert(
        this.props.screenProps.chinese?`每个订单只能使用一种促销方式`:`You can only use one promotion at a time`,
        this.props.screenProps.chinese?``:`Continue will drop applied promo code: ${this.props.navigation.state.params.promoCode.name}.`,
        [
          {text: this.props.screenProps.chinese?'取消':'Cancel'},
          {text: this.props.screenProps.chinese?'继续':'Continue', onPress: () => {
            this.props.navigation.setParams({promoCode: null});
            this.onConfirmSelectVoucher();
          }},
        ],
        { cancelable: true }
      );
    } else {
      this.onConfirmSelectVoucher();
    }
  }
  onConfirmSelectVoucher = () => {
    const navigation = this.props.navigation;
    navigation.navigate('Vouchers', {available:true,selectMode:true,voucher: navigation.state.params.voucher, onSelect: (voucher) => {
      setTimeout(() => {
        navigation.setParams({
          voucher
        });
      }, 100);
    }});
  }
  onSelectPromocode = () => {
    if (this.props.navigation.state.params.voucher) {
      Alert.alert(
        this.props.screenProps.chinese?`每个订单只能使用一种促销方式`:`You can only use one promotion at a time`,
        this.props.screenProps.chinese?``:`Continue will deselect selected voucher: ${this.props.navigation.state.params.voucher.title}.`,
        [
          {text: this.props.screenProps.chinese?'取消':'Cancel'},
          {text: this.props.screenProps.chinese?'继续':'Continue', onPress: () => {
            this.props.navigation.setParams({voucher: null});
            this.onConfirmSelectPromoCode();
          }},
        ],
        { cancelable: true }
      );
    } else {
      this.onConfirmSelectPromoCode();
    }
  }
  onPriceChange = (toPayPrice) => {
    this.setState({toPayPrice});
  }
  onConfirmSelectPromoCode = () => {
    const navigation = this.props.navigation;
    navigation.navigate('PromoCode', {type: navigation.state.params.type, promoCode: navigation.state.params.promoCode, onSelect: (promoCode) => {
      setTimeout(() => {
        navigation.setParams({
          promoCode
        });
      }, 100);
    }});
  }
  render() {
    const { type, items, pickupDate, deliveryDate, addressId, deliveryAddressId,
      voucher, promoCode, payment, business, capture, userId } = this.props.navigation.state.params;
    const { chinese } = this.props.screenProps;
    const isTopup = type==='topup';

    return (
      <ScrollView>
        <Text style={styles.header}>{chinese?'支付方式':'Payment Options'}</Text>
        <List containerStyle={styles.list}>
          {!isTopup&&
            <CreditPaymentOption userId={userId} type={type} items={items} pickupDate={pickupDate} deliveryDate={deliveryDate}
              addressId={addressId} deliveryAddressId={deliveryAddressId} voucherId={voucher&&voucher.id}
              promoCodeId={promoCode&&promoCode.id}
              select={payment} onSelect={this.onSelectCredit} chinese={chinese} navigation={this.props.navigation}
              onPriceChange={this.onPriceChange}/>
          }
          <CreditCardList userId={userId} hideEmpty nolist hideFooter style={styles.list} chinese={chinese} select={payment}
            selectMode onSelect={this.onSelectCreditCard}/>
          {!isTopup&&!capture&&['laundry','premiumlaundry'].indexOf(type)>=0&&
            <ListItem leftIcon={{name:'money',type:'font-awesome'}} title='Cash' subtitle='Cash on Delivery' onPress={this.onSelectCash}
              rightIcon={{name:payment==='cash'?'radio-button-checked':'radio-button-unchecked',color:payment==='cash'?primaryColor:null}}/>
          }
        </List>
        {!isTopup&&!business&&<Text style={styles.header}>{chinese?'促销':'Promotions'}</Text>}
        {!isTopup&&!business&&
          <List containerStyle={styles.list}>
            <ListItem title={voucher?voucher.title:(chinese?'(未选择)':'(Unselected)')} hideChevron={promoCode?true:false}
              subtitle={voucher?`$${voucher.value} ${chinese?'折扣':'discount'}`:(chinese?'点击选择优惠券':'Click to select voucher')}
              onPress={this.onSelectVoucher}/>
            <ListItem title={(promoCode&&promoCode.name)?promoCode.name:(chinese?'(未使用)':'(Unapplied)')} hideChevron={voucher?true:false}
              subtitle={promoCode?`${(promoCode.promoType=='1')?`$${promoCode.flatDiscount}`:`${promoCode.discountPercent}%`} ${chinese?'折扣':'discount'}`:(chinese?'点击输入优惠码':'Click to enter promo code')} 
              onPress={this.onSelectPromocode}/>
          </List>
        }
      </ScrollView>
    );
  }
}

export default CheckoutPaymentPage;


